//
//  TimeUtils.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/1/11.
//

import Foundation

//传参不限制毫秒还是秒
class TimeUtils {
    //转换时间戳
    static func getDate(time: TimeInterval,format: String) -> String {
        // 将毫秒转换为秒
        let timestampInSeconds = getSecond(time: time)
        let date = Date(timeIntervalSince1970: timestampInSeconds)
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = format
        
        let formattedDate = dateFormatter.string(from: date)
        return formattedDate
    }
    
    static func getDate(time: Int64,format: String) -> String {
        return getDate(time: TimeInterval(time), format: format)
    }
    
    static func getDate(date: Date,format: String) -> String {
        let timestampInSeconds = date.timeIntervalSince1970
        let date = Date(timeIntervalSince1970: timestampInSeconds)
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = format
        
        let formattedDate = dateFormatter.string(from: date)
        return formattedDate
    }
    
    static func isToday(_ time: TimeInterval) -> Bool {
        // 将毫秒转换为秒
        let timestampInSeconds = getSecond(time: time)
        let date = Date(timeIntervalSince1970: timestampInSeconds)
        let calendar = Calendar.current
        return calendar.isDateInToday(date)
    }
    
    static func isSameMonth(_ time: TimeInterval, _ time2: TimeInterval) -> Bool {
        if getDate(time: time, format: "yyyy-MM") == getDate(time: time2, format: "yyyy-MM") {
            return true;
        }
        return false;
    }
    
    static func isSameYear(_ time: TimeInterval, _ time2: TimeInterval) -> Bool {
        if getDate(time: time, format: "yyyy") == getDate(time: time2, format: "yyyy") {
            return true;
        }
        return false;
    }
    
    /**
     * 定义一个函数来获取指定时间是所在月份的第几周
     */
    static func getMonthWeek(time: TimeInterval) -> Int {
        // 将毫秒转换为秒
        let timestampInSeconds = getSecond(time: time)
        let date = Date(timeIntervalSince1970: timestampInSeconds)
        // 精确对齐 Android 的 Calendar 配置
        var calendar = Calendar(identifier: .gregorian)
        calendar.firstWeekday = 1 // 周日作为每周第一天 (Sunday = 1)
        calendar.minimumDaysInFirstWeek = 1 // 首周只需1天
        return calendar.component(.weekOfMonth, from: date)
    }
    
    // 将秒数转换为 00:00 格式的方法
    static func formatTime(seconds: Int) -> String {
        let minutes = seconds / 60
        let remainingSeconds = seconds % 60
        return String(format: "%02d:%02d", minutes, remainingSeconds)
    }
    
    static func getDiffMinute(_ time:Int64, _ time2:Int64) -> Int {
        let diff = abs(getSecond(time: time) - getSecond(time: time2));  //获取时间差
        return Int(diff / 60);
    }
    
    
    static func getTimeStr(time: Int64) -> String {
        if time == 0 {
            return ""
        }
        let curDate = Date()
        let time = getSecond(time: time)
        let timeDate = Date(timeIntervalSince1970: time)
        // 检查是否是今天的某个时间
        if TimeUtils.isToday(time) {
            return TimeUtils.getDate(time: time, format: "HH:mm")
        }
        // 检查是否是昨天的某个时间
        if timeDate.isYesterday() {
            return "昨天 \(TimeUtils.getDate(time: time, format: "HH:mm"))"
        }
        // 检查是否是本周的某个时间
        if timeDate.isSameWeek(as: curDate) {
            let dateFormatter = DateFormatter()
            dateFormatter.locale = Locale(identifier: "zh_CN")
            dateFormatter.dateFormat = "EEEE"
            let weekDay = dateFormatter.string(from: timeDate)
            return "\(weekDay) \(TimeUtils.getDate(time: time, format: "HH:mm"))"
        }
        // 检查是否是同一年
        if timeDate.isSameYear(as: curDate) {
            return TimeUtils.getDate(time: time, format: "MM-dd HH:mm")
        }
        return TimeUtils.getDate(time: time, format: "yyyy-MM-dd HH:mm")
    }
    
    static func getDiffDay(time: TimeInterval, time2: TimeInterval) -> Int {
        // 计算时间差（秒），取绝对值
        let diff = abs(getSecond(time: time) - getSecond(time: time2))
        // 转换为天数并四舍五入
        let days = diff / (3600 * 24)
        return Int(days.rounded())
    }
    
    
    static func getWeekStr(time: TimeInterval) -> String {
        return getWeekStr(time: getMillisecond(time))
    }
    
    static func getWeekStr(time: Int64) -> String {
        // 将毫秒转换为秒（Swift的TimeInterval以秒为单位）
        let timestampInSeconds = getSecond(time: time)
        
        // 创建日期对象
        let date = Date(timeIntervalSince1970: timestampInSeconds)
        
        // 配置日期格式化器
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "zh_CN") // 设置中文 locale
        //"EEEE" 表示完整的星期名称（如 "星期一"）"EEE" 表示缩写的星期名称（如 "周一"）
        formatter.dateFormat = "EEE" // 缩写的星期名称
        
        return formatter.string(from: date)
    }
    
    /// 将时间戳转换为对应的时间段（凌晨、早上、上午等）
    /// - Parameter time: 时间戳（毫秒）
    /// - Returns: 时间段字符串
    static func getTimePeriod(time: Int64) -> String {
        // 将毫秒转换为秒（Swift的TimeInterval以秒为单位）
        let timeInSeconds = getSecond(time: time)
        let date = Date(timeIntervalSince1970: timeInSeconds)
        
        // 获取小时数（24小时制）
        let calendar = Calendar.current
        let hour = calendar.component(.hour, from: date)
        
        // 根据小时判断时间段
        switch hour {
        case 0..<6:
            return "凌晨"
        case 6..<9:
            return "早上"
        case 9..<12:
            return "上午"
        case 12:
            return "中午"
        case 13..<18:
            return "下午"
        case 18..<20:
            return "傍晚"
        default: // 20..<24
            return "晚上"
        }
    }
    
    
    /// 计算两个时间戳的差值并返回中文描述（如 "2天3小时"、"1小时" 等）
    static func getDiffDayStr2(time: Int64, time2: Int64) -> String {
        // 转换为秒并计算绝对值差值
        let diffSeconds = abs(getSecond(time: time) - getSecond(time: time2))
        if diffSeconds <= 0 {
            return "0秒"
        }
        
        // 时间单位换算
        let secondsPerMinute: TimeInterval = 60
        let secondsPerHour: TimeInterval = 3600
        let secondsPerDay: TimeInterval = secondsPerHour * 24
        
        // 计算天数和剩余秒数
        let days = Int(diffSeconds / secondsPerDay)
        let remainingSecondsAfterDays = diffSeconds.truncatingRemainder(dividingBy: secondsPerDay)
        
        // 计算小时数
        let hours = Int(remainingSecondsAfterDays / secondsPerHour)
        
        // 1. 存在天数
        if days > 0 {
            return hours > 0 ? "\(days)天\(hours)小时" : "\(days)天"
        }
        
        // 2. 无天数但有小时数
        if hours > 0 {
            return "\(hours)小时"
        }
        
        // 3. 无小时但有分钟数
        let minutes = Int(remainingSecondsAfterDays / secondsPerMinute)
        if minutes > 0 {
            return "\(minutes)分钟"
        }
        
        // 4. 剩余秒数
        return "\(Int(remainingSecondsAfterDays))秒"
    }
    
}
